package org.springside.examples.miniweb.web.user;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springside.examples.miniweb.entity.user.User;
import org.springside.examples.miniweb.service.user.UserManager;
import org.springside.modules.web.struts2.CRUDAction;

/**
 * 用户管理Action. 本Action演示完整的Struts2 Action写法.继承于CRUDAction的更简单版本见{RoleAction}.
 * 
 * @author calvin
 */
@SuppressWarnings(
{ "serial", "unchecked" })
public class UserAction extends CRUDAction<User>
{

	public static final String TEST = "test";

	private UserManager userManager;

	private Integer id;

	private Integer[] roleId;

	private Integer test;

	public String forwardLogin()
	{
		return SUCCESS;
	}

	public String login() throws Exception
	{
		if (userManager.auth(this.entity.getLoginName(), this.entity.getPassword()))
		{
			return ERROR;
		} else
		{
			return TEST;
		}
	}

	public void setId(Integer id)
	{
		this.id = id;
	}

	public void setUserManager(UserManager userManager)
	{
		this.userManager = userManager;
	}

	@Override
	protected Object getManager()
	{
		return userManager;
	}

	@Override
	protected Integer getId()
	{
		return id;
	}

	@Override
	protected void onDisplayPrepare()
	{
		if (this.queryCondition.length() > 0)
			this.params.put("loginName", this.queryCondition);
	}

	@Override
	protected void onSavePrepare()
	{
		if (roleId != null)
		{
			this.entity.getRoles().clear();
			for (int i = 0; i < roleId.length; i++)
			{
				this.entity.getRoles().add(userManager.getRole(roleId[i]));
			}
		}
	}

	@Override
	protected void onInputPrepare()
	{
		Map extendAttributes = new HashMap();
		List allRoles = userManager.getAllRole();
		extendAttributes.put("allRoles", allRoles);
		this.entity.setExtendAttributes(extendAttributes);
	}

	public Integer getTest()
	{
		return test;
	}

	public void setTest(Integer test)
	{
		this.test = test;
	}

	public Integer[] getRoleId()
	{
		return roleId;
	}

	public void setRoleId(Integer[] roleId)
	{
		this.roleId = roleId;
	}
}
